package server.whiteboard;


import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

import java.util.stream.Stream;

public class WbRequestHandler {

    public final static String actionPath = "action";

    public static void handle(WhiteBoardRequestThread.RequestContext rct) {
        //从请求URL中解析出要加载的action方法，例：/user/login => action.UserAction的login方法
        String[] classAndMethod = Stream.of(rct.getRequestURL().split("/")).filter(p -> p.length()>0).toArray(String[]::new);
        String cls = classAndMethod[0];
        cls = Character.toUpperCase(cls.charAt(0)) + cls.substring(1) + "Action";
        String actionClassPath = actionPath + "." + cls;
        classAndMethod[0] = actionClassPath;
        invokeMethod(classAndMethod[0], classAndMethod[1], rct);
    }


    /**
     * 通过类名和方法名调用对应的方法（Java反射）
     */
    public static void invokeMethod(String actionClassPath, String methodName, WhiteBoardRequestThread.RequestContext rct) {
        try {
            Object action = Class.forName(actionClassPath).newInstance();
//            Method method = action.getClass().getMethod(methodName, Map.class);
            Method method = getActionMethod(action.getClass(), methodName);
            method.invoke(action, rct);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 根据方法名返回方法的实例（不允许action方法重名）
     */
    private static <T> Method getActionMethod(Class<T> cls, String method) {
        for (Method m : cls.getDeclaredMethods()) {
            if (Modifier.isPublic(m.getModifiers()) && m.getName().equals(method))
                return m;
        }
        return null;
    }
}
